<?php


namespace app\store\model\dealer;

use app\common\model\dealer\Record as RecordModel;
use app\store\model\User as BaseUserModel;
use app\store\model\dealer\User as UserModel;
use app\common\exception\BaseException;
class Record extends RecordModel
{
    /**
     * 统计级差
     */
    public static  function calculation(){
        $static = new static();
        //保存已经清空级差累计流水的用户 user_id
        $delete_level_array = [];
        //统计数据
        $tem_array = [];
        //查询开启级差用户
        $users = UserModel::with(['user'])->where(['is_level'=>1])->select();
        //查询上线是该用户的用户
        if (!$users){
            //没有开启级差的用户
            $static->error = '没有开启级差的用户';
            return false;
        }
        //进行数据写入
        foreach ($users as $k=>$v){
            if (!(float)$v['user']['level_money']){
                continue;
            }
            $res  = $static->statisticsLevel($v->user_id,$v['user']['level_money']);
            //清空累计数据
            $delete_level_money = [];
            //start事务
            $static->startTrans();
            try {
                $record_data = [
                    'user_id'=>$v->user_id,
                    'money'=>$res['money'],
                    'royalty'=>$res['all_royalty'],
                    'level'=>$res['level'],
                    'level_royalty'=>$res['royalty'],
                    'wxapp_id' => $static::$wxapp_id,
                    'settle_time'=>time()
                ];
                $record = $static->save($record_data);
                if ($record){
                    //判断当前用户是否加入
                    if ($static->checkClearLevel($v->user_id,$delete_level_array,1)){
                        $delete_level_money[] = $v->user_id;
                    }
                    $record_id = $static->id;
                    foreach ($res['level_user'] as $kl=>$vl){
                        $record_data_log = [
                            'record_id'=> $record_id,
                            'user_id'=>$kl,
                            'money'=>$vl['money'],
                            'royalty'=>$vl['user_level_money'],
                            'level'=>$vl['level'],
                            'wxapp_id' => $static::$wxapp_id,
                            'level_royalty'=>$vl['royalty']
                        ];
                        $log = new RecordLog();
                        if ($log->save($record_data_log) && !in_array($kl,$delete_level_money)){
                            //判断用户是否加入
                            if ($static->checkClearLevel($kl,$delete_level_array,2)){
                                $delete_level_money[] = $kl;
                            }
                        }
                    }
                }
                //清空相关数据累计级差流水
                foreach ($delete_level_money as $kd=>$vd){
                    $userModel =  BaseUserModel::detail($vd);
                    $userModel->level_money = 0;
                    //加入已清空级差累计用户数组
                    if ($userModel->save()){
                        $delete_level_array[] = $vd;
                    }

                }
                //加入可提现金额
                $dealerModel = new UserModel;
                $dealer = $dealerModel->find($v->user_id);
                $dealer->money = $dealer->money + $res['all_royalty'];
                $dealer->save();
                $static->commit();
                continue;
            } catch (\Exception $e) {
                $static->rollback();
                $static->error = '级差统计异常';
                throw new BaseException(['msg' => $e->getMessage()]);
            }
        }
        return true;
    }

    /**
     * 判断是否加入清空级差累计用户
     * @param $user_id 用户编号
     * @param $delete_array 可清空id
     * @param int $type 类型 1为当前用户 2为下线用户
     * @return bool
     */
    private function checkClearLevel($user_id,$delete_array,$type = 1){
        $res = false;
        //当前用户
        if ($type == 1){
            $user =  BaseUserModel::detail($user_id);
            //判断是否存在上线
            if ($user->level_id){
                //存在-判断是否已存在于处理数组中 $delete_array
                if (in_array($user->level_id,$delete_array)){
                    //已处理
                    //返回true
                    $res = true;
                }else{
                    //未处理返回 false
                    $res = false;
                }
            }else{
                //不存在返回 true
                $res = true;
            }
        }
        //下线用户
        if ($type == 2){
            $users = UserModel::where(['is_level'=>1,'user_id'=>$user_id])->find();
            //判断是否是级差用户
            if ($users){
                if (in_array($user_id,$delete_array)){
                    //已处理返回true
                    $res = true;
                }else{
                    //未处理返回 false
                    $res = false;
                }
            }else{
                //不是级差用户返回true
                $res = true;
            }
        }
        return $res;
    }

    /**
     * 统计用户总提成及下线数据
     * @param $user_id    用户编号
     * @param $user_level_money  用户累计流水
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function statisticsLevel($user_id,$user_money){
        //计算用户所在级别及提成点
        $user_level =  operationlevel($user_money);
        //Array ( [level] => 2 [royalty] => 4 )
        $userModel = new BaseUserModel();
        //统计下线数据
        $list_level = $userModel->where(['level_id'=>$user_id])->select();
        //临时变量-存储总提成
        $all_royalty = 0;
        //临时变量-存储处理好的下线数据
        $level_array = [];
        //临时变量-存储用户自己业绩
        $self_money = $user_money;
        foreach ($list_level as $k=>$v){
            $tem_level = operationlevel($v['level_money']);
            $self_money = $self_money - $v['level_money'];
            //用户级差提成
            if ($user_level['level'] - $tem_level['level'] > 0){
                $tem_level['user_level_money'] = $v['level_money']*($user_level['royalty']-$tem_level['royalty'])*0.0001;
            }else{
                $tem_level['user_level_money'] = 0;
            }
            $tem_level['money'] = $v['level_money'];
            $tem_level['level_royalty'] = $user_level['royalty']-$tem_level['royalty'];
            //统计累计提成
            $all_royalty = $all_royalty+$tem_level['user_level_money'];
            //将数据存储
            $level_array[$v['user_id']] =  $tem_level;
        }
        //用户自己的贡献
        if ($user_money > 0){
            $level_array[$user_id] = ['level'=>$user_level['level'],
                                    'royalty'=>$user_level['royalty'],
                                    'user_level_money'=>$self_money*$user_level['royalty']*0.0001,
                                    'money'=>$self_money,
                                    'level_royalty'=>$user_level['royalty']];
        }
        return ['all_royalty'=>$all_royalty+($user_level['royalty']*$self_money*0.0001),'money'=>$user_money,'level'=>$user_level['level'],'royalty'=>$user_level['royalty'],'level_user'=>$level_array];
    }

    /**
     * 查看级差记录
     * @param $user_id
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($user_id){
        $list = $this->with(['user'])->where(['user_id'=>$user_id])
                ->paginate(15, false, [
            'query' => \request()->request()
        ]);
        return $list;
    }
}